﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;

using NJ.Common.Web;
using NJ.Dto.RoleMenu;
using NJ.Service.Menu;
using NJ.Web.ViewModel;
namespace NJ.Web.Controllers
{
    public class MenuController : Controller
    {
        private readonly IMenuService menuService;
        public MenuController(IMenuService _menuService)
        {
            menuService = _menuService;
        }
        // GET: Menu
        public ActionResult Index()
        {
            return View();
        }
        #region 获取菜单
        public async Task<ActionResult> GetMenusAsync()
        {
            List<MenuTreeViewModel> GetMenuTree(int pid, List<MenuDto> menuDtos)
            {
                List<MenuTreeViewModel> menuTreeViewModels = new List<MenuTreeViewModel>();
                var children = menuDtos.Where(t => t.PId == pid);
                foreach (var child in children)
                {
                    var m = new MenuTreeViewModel
                    {
                        Icon = child.Icon,
                        Id = child.Id,
                        PId = child.PId,
                        Title = child.Title,
                        Url = child.Url,
                        Level = child.Leader.Where(t => t == '-').Count() + 1,
                        Leader = child.Leader,
                        Children = GetMenuTree(child.Id, menuDtos)
                    };
                    menuTreeViewModels.Add(m);
                }
                return menuTreeViewModels;
            }

            var list = await menuService.GetMenusAsync();
            var tree = GetMenuTree(0, list);
            return Json(new HttpResult { data = tree, status = ResultState.success }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        public async Task<ActionResult> Add(int Id)
        {
            var list = await menuService.GetParentMenusAsync(Id);
            return View(list);
        }

        public async Task<ActionResult> Edit(int Id, int Pid)
        {
            var menu = await menuService.GetMenuAsync(Id);
            var list = await menuService.GetParentMenusAsync(Pid);
            var model = new MenuViewModel
            {
                menu = menu,
                parent = list
            };
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public async Task<ActionResult> SaveAsync(CreateOrUpdateMenuDto dto)
        {
            int Id = await menuService.SaveMenuAsync(dto);
            return Json(new HttpResult { status = ResultState.success, data = Id });
        }

        [HttpPost]
        public async Task<ActionResult> DeleAsync(int Id)
        {
            bool result = await menuService.DeleMenuAsync(Id) > 0;
            return Json(new HttpResult { status = ResultState.success, data = result });
        }
    }
}